<?php
define('CONFIG_FILE_LOCATION', 'lib/Config.class.php', true);
if(file_exists(CONFIG_FILE_LOCATION))
{
	require CONFIG_FILE_LOCATION;
	require 'lib/Database.class.php';
	require 'lib/Main.class.php';
	require 'lib/facebook.php';

}
else
{
	die("Ebaõnn!");
}
session_start();
$config = new Config();
$main = new Main($config);
$facebook = new Facebook(array(
  'appId'  => '313932678665167',
  'secret' => '6c9c9f7dec245892a84b18dd79c9bce9',
  'cookie' => true
));
$user = $facebook->getUser();
if($_GET['logout'] == "true") {
	session_destroy();
	header("Location:https://www.gotoandplay.ee/battleships/");	
}
if($user && empty($_SESSION['user_logged_in'])) {
	$content = file_get_contents('http://graph.facebook.com/' . $facebook->getUser());
	$parsed  = json_decode($content);
	$id = $main->query_first("SELECT id FROM bs_users WHERE facebook_id = '" . $parsed->id . "'");
	if(empty($id) && $parsed->id && $parsed->name) {
		$insert['facebook_id'] = $parsed->id;
		$insert['facebook_name'] = $parsed->name;
		if($main->query_insert("users",$insert));
		$id['id'] = mysql_insert_id();
	}
	if(!empty($id)) {
		$_SESSION['user_logged_in'] = $id['id'];
	}
	header("Location:https://www.gotoandplay.ee/battleships/");
}
include 'lib/xajax/xajax_core/xajax.inc.php';
$xajax = new xajax();
include 'lib/xajax.php';
$xajax->processRequest();
if($_SESSION['user_logged_in']) {
	$main->updateActivity();	
}
?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns:fb="http://ogp.me/ns/fb#">
<head>
<title>Battleships by Pärt Erikson & Allar Vallaots</title>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<meta property="og:title" content="Battleships"/>
<meta property="og:description" content="Play battleships free!"/>
<meta property="og:url" content="https://www.gotoandplay.ee/battleships/"/>
<meta property="og:image" content="https://www.gotoandplay.ee/battleships/images/logo.jpg"/>
<meta property="fb:app_id" content="313932678665167"/>
<link type="text/css" rel="stylesheet" href="default.css" media="all" />
<?php $xajax->printJavascript("lib/xajax"); ?> 
<script type="text/javascript">
var activeType = 0;
var activeRotation = 0;
var ship = new Array();
var collide = false;
var ships = 0;
var interval;
function init() {
	xajax_init();
	setInterval(xajax_lobby,2500);
}
function closePopup() {
	document.getElementById("popup").style.display = "none";	
}
function openWindow(adr, target) {
	window.open(adr,target); 
}
function startGame() {
	document.getElementById("game_table").style.display = "block";
	if(interval) {
		clearInterval(interval);	
	}
	interval = setInterval(xajax_updateGame,1000);
	xajax_updateGame();
}
function rotateShip() {
	if(activeRotation == 0) {
		activeRotation = 1;	
		document.getElementById('rotator').innerHTML = "Laev vertikaalselt";
	}else  {
		activeRotation = 0;
		document.getElementById('rotator').innerHTML = "Laev horisontaalselt";
	}
}
function gridClick(x,y) {
	if(activeType == 0) {
		
	}else {
		if(collide == false) {
			for(var i = 0;i<ship.length;i++) {
				ship[i].setAttribute("oldclass","shipActive");
				ship[i].setAttribute("x",x);
				ship[i].setAttribute("y",y);
				ship[i].setAttribute("type",activeType);
				ship[i].setAttribute("angle",activeRotation);
			}
			deactivateShip(x,y);
			ships ++;
		}
	}
	gridOut(x,y);
	if(ships >= 10) {
		document.getElementById("start_game_button").style.display = "block";	
	}
}
function collision(x, y) {
	ship = new Array();
	collide = false;
	//test same space
	for(var i = 0;i<activeType;i++) {
		var grid;
		if(activeRotation == 0) {
			grid = document.getElementById("grid"+x+""+(y+i));
		}else{
			grid = document.getElementById("grid"+(x+i)+""+y);
		}
		if(grid) {
			if(grid.getAttribute('type')) {
				collide = true;
			}
		}else {
			collide = true;	
		}
		if(grid) {
			ship.push(grid);
		}
	}
	testspace(x,y,1,0);
	testspace(x,y,-1,0);
	testspace(x,y,0,1);
	testspace(x,y,0,-1);
	for(var i = 0;i<ship.length;i++) {
		ship[i].setAttribute("oldclass", ship[i].className);
		if(collide == true) {
			ship[i].className = "shipCollision";
		}else {
			ship[i].className = "shipOver";
		}
	}
}
function testspace(x,y,space1,space2) {
	for(var i = 0;i<activeType;i++) {
		var grid;
		if(activeRotation == 0) {
			grid = document.getElementById("grid"+(x+space1)+""+(y+i+space2));
		}else{
			grid = document.getElementById("grid"+(x+i+space2)+""+(y+space1));
		}
		if(grid) {
			if(grid.getAttribute('type')) {
				collide = true;
			}
		}
	}
}
function gridOver(x, y) {
	if(activeType != 0){ 
		collision(x, y)
	}
}
function gridOut(x, y) {
	for(var i = 0;i<ship.length;i++) {
		ship[i].className = ship[i].getAttribute("oldclass");
	}
}
function activateShip(type, obj) {
	var active = document.getElementById("activeShip");
	if(active) {
		active.id = "";
	}
	activeType = type;
	obj.id = "activeShip";
}
function deactivateShip(x,y) {
	var active = document.getElementById("activeShip");
	if(active) {
		active.style.display = "none";
		active.id = "deactive"+x+""+y;
		activeType = 0;
	}
}
function startBattleships() {
	var arr = new Array();
	for(var i = 0;i<10;i++) {
		for(var j = 0;j<10;j++) {
			var obj = document.getElementById("grid"+j+i);
			if(obj.getAttribute("type")) {
				arr.push(new Array(j,i,obj.getAttribute("type"),obj.getAttribute("angle")));
			}else {
				arr.push(new Array(j,i,0,0));
			}
		}
	}
	xajax_battleship(arr);
}
</script>
</head>
<body onload="init();">
<!-- HTML -->
<div id="app-battleships-520px">
    <div id="popup">
    	<div id="popup_area">
        	<a class="close_button" href="javascript:closePopup();">close</a>
    		<div id="popup_message"></div>
        </div>
    </div>
	<!-- Header -->
    <div id="header">
    	<h1>BattleShips</h1>
    </div>
    <!-- Main -->
    <div id="main">
    	<?php if(isset($_SESSION['user_logged_in'])) { ?>
        <div id="game_area">
        	<div id="game_info">
            	Valige mäng millega liituda!
            </div>
        	<div id="game_table">
                <div class="game_header">Sinu laevastik</div>
                <div id="game_buttons">
                	<div class="game_info">Paiguta laevastik</div>
                	<div id="ships">
                        <div class="ship ship1" onclick="activateShip(1, this);">1x</div>
                        <div class="ship ship1" onclick="activateShip(1, this);">1x</div>
                        <div class="ship ship1" onclick="activateShip(1, this);">1x</div>
                        <div class="ship ship1" onclick="activateShip(1, this);">1x</div>
                        <div class="ship ship2" onclick="activateShip(2, this);">2x</div>
                        <div class="ship ship2" onclick="activateShip(2, this);">2x</div>
                        <div class="ship ship2" onclick="activateShip(2, this);">2x</div>
                        <div class="ship ship3" onclick="activateShip(3, this);">3x</div>
                        <div class="ship ship3" onclick="activateShip(3, this);">3x</div>
                        <div class="ship ship4" onclick="activateShip(4, this);">4x</div>
                        <div class="clear"></div>
                    </div>
                    <div class="ship" onclick="rotateShip();" id="rotator">Laev vertikaalselt</div>
                    <div class="ship" onclick="startBattleships();" id="start_game_button">Alusta mängu</div>
                    <div class="clear"></div>
                </div>
                <div id="gametable"></div>
                <div class="game_header">Vastase laevastik</div>
                <div id="info_header"></div>
                <div id="gametable_opponent"></div>
            </div>
        </div>
        <div id="lobby">
        </div>
        <div class="clear"></div>
        <?php } else { ?>
        <div class="center" style="padding:20px;">
        <p>Mängu alustamiseks tuleb sisse logida</p>
        </div>
        <?php } ?>
        <div id="footer">
       		<div class="center">
            	<fb:login-button autologoutlink="true" show-faces="false" width="200" max-rows="1"></fb:login-button>
            </div>
        </div>
    </div>
</div>
<!-- JAVASCRIPT -->
<!-- Initialize the fb javascript SDK -->
<script>
  window.fbAsyncInit = function() {
    FB.init({ appId: '313932678665167', 
              status: true, 
              cookie: true,
              xfbml: true,
              oauth: true}); 
	FB.Event.subscribe('auth.login', function (response) {
                window.location = "https://www.gotoandplay.ee/battleships/?login=true";
            });
    FB.Event.subscribe('auth.logout', function (response) {
                window.location = "https://www.gotoandplay.ee/battleships/?logout=true";
            });
  };
</script>
<!-- fb javascript SDK import -->
<div id="fb-root"></div>
<script>
  (function() {
    var e = document.createElement('script'); e.async = true;
        e.src = document.location.protocol + '//connect.facebook.net/et_EE/all.js';
        document.getElementById('fb-root').appendChild(e);
        }());
</script>
</body>
</html>